package org.goyo.main.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.octo.captcha.image.ImageCaptcha;

public class LoginCodeFilter implements Filter{
	
	ImageCaptcha imageCaptcha = null;
	
	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpSession session = request.getSession(); 
		String validateCode = request.getParameter("j_captcha");
		ImageCaptcha imageCaptcha = (ImageCaptcha) session.getAttribute("imageCaptcha");
	    boolean flag = (imageCaptcha.validateResponse(validateCode)).booleanValue();

		if (flag) {
			filterChain.doFilter(request, response);
		} else {
			response.sendRedirect("/system/login?login_error=2");
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		ServletContext context = arg0.getServletContext();
		
	}

}
